package com.bbs.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bbs.dao.ArticleDao;
import com.bbs.dao.BlocksDao;
import com.bbs.entity.Article;
import com.bbs.entity.Collection;
import com.bbs.entity.Reply;
import com.bbs.entity.User;
import com.bbs.service.ArticleService;
import com.bbs.service.CollectionService;
import com.bbs.service.ModeratorService;
import com.bbs.service.ReplyService;
import com.bbs.service.UserService;
import com.bbs.util.ChangeUtil;
import com.bbs.util.DateUtil;
import com.bbs.util.Page;

public class ArticleServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_method");
		if(method.equals("create")){
			create(request,response);
		} else if("show".equals(method)) {
			show(request, response);
		} else if("settop".equals(method)) {
			settop(request,response);
		} else if("findMine".equals(method)){
			findMine(request,response);
		} else if("delete".equals(method)) {
			delete(request,response);
		} else if("collection".equals(method)) {
			collection(request, response);
		} else {
			response.sendError(404);
		}
	}
	
	private void collection(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String aid = request.getParameter("id");
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		Collection col = new Collection(); 
		col.setAid(new ChangeUtil().changeStringToInt(aid));
		col.setUid(u.getId());
		col.setCreatedate(DateUtil.getNow());
		new CollectionService().save(col);
		response.sendRedirect("article.jspx?_method=show&id="+aid);
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String aid = request.getParameter("id");
		String bid = request.getParameter("bid");
		ChangeUtil cu = new ChangeUtil();
		
		int id = cu.changeStringToInt(aid);
		
		HttpSession session = request.getSession();
		User u = (User)session.getAttribute("user");
		if(u.getRole() == 2) {
			new ReplyService().deleteByAid(id);
			new ArticleService().deleteById(id);
			response.sendRedirect("blocks.jspx?_method=show&id="+bid);
		} else {
			response.sendError(404);
		}
	}

	/**
	 * 找到用户的帖子
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void findMine(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		User u = (User) request.getSession().getAttribute("user");
		String page = request.getParameter("p");
		Page p = new Page();
		p.setTotleSize(new ArticleDao().getMyCount(u));
		p.setPageSize(10);
		if(page != null){
			p.setCurrentPage(Integer.parseInt(page));
		}
		List<Article> alist = new ArticleService().findMineByUid(u.getId(),p);
		if(alist == null){
			alist = new ArrayList<Article>();
		}
			request.getSession().setAttribute("alist", alist);
			request.getSession().setAttribute("page", p);
			response.sendRedirect("index.jspx?_method=usercenter");
	}

	/**
	 * 版主置顶id为？的帖子
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void settop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
		String id = request.getParameter("id");
		String bid = request.getParameter("bid");
		String uid = request.getParameter("userid");
		ChangeUtil cu = new ChangeUtil();
		int userid = cu.changeStringToInt(uid);
		int aid = cu.changeStringToInt(id);
		if(aid == 0 || userid == 0) {
			response.sendError(404);
		} else {
			if(new ModeratorService().findByUid(userid) != null && new ArticleService().settop(aid) > 0) {
				response.sendRedirect("blocks.jspx?_method=show&id="+bid);
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("bemsg", "置顶失败！");
				response.sendRedirect("blocks.jspx?_method=show&id="+bid);
			}
		}
	}

	/**
	 * 通过id，page显示帖子
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void show(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ArticleService articleService = new ArticleService();
		String id = request.getParameter("id");
		String pid = request.getParameter("page");
		ChangeUtil cu = new ChangeUtil();
		int p;
		if(pid == null) {
			p = 1;
		} else {
			p = cu.changeStringToInt(pid);
		}
		Page page = new Page();
		page.setPageSize(10);
		page.setTotleSize(new ReplyService().findReplyCount(id));
		page.setCurrentPage(p);
		if(p > 0 && p <= page.getTotlePages()) {
			Article article = articleService.findById(Integer.valueOf(id),page);
			if(p == 1) {
				article.setClickNum(article.getClickNum() + 1);
			}
			int rows = articleService.update(article);
			if(rows > 0) {
				HttpSession session = request.getSession();
				session.setAttribute("article", article);
				session.setAttribute("page", page);
				response.sendRedirect("index.jspx?_method=showarticle&id="+id+"&page="+p);
			} else {
				response.sendError(404);
			}
		} else {
			response.sendRedirect("index.jspx?_method=showarticle&id=0&page=0");
		}
	}
	
	/**
	 * 发表新帖
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String title = request.getParameter("title");
		String blocksid = request.getParameter("blocksid");
		String content = request.getParameter("content");
		Article a = new Article();
		ChangeUtil cu = new ChangeUtil();
		int bid = cu.changeStringToInt(blocksid);
		a.setBlocks(new BlocksDao().findById(bid));
		a.setContent(content);
		a.setCreatedate(DateUtil.getNow());
		new DateUtil();
		a.setCreatedate(DateUtil.getNow());
		a.setName(title);
		User u = (User)request.getSession().getAttribute("user");
		u.setScore(u.getScore() + 2);
		a.setUser(u);
		new UserService().update(u);
		int row = new ArticleService().save(a);
		System.out.println(row);
		if(row > 0) {
			response.sendRedirect("blocks.jspx?_method=show&id="+blocksid);
		} else {
			response.sendError(404);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}

}
